const fs = require('fs');
const path = require('path');
const chalk = require('chalk'); //命令行输出样式美化
const inquirer = require('inquirer'); //命令行交互
const checkDire = require('../utils/checkDire.js');
const copyfile = require('../utils/copyfile.js');
const config = require('../config.js');
const packageName = require("../packageName.json")
const {
  promptTypeList
} = require('../config.js');

module.exports = async (projectName, cmd) => {
  const pathName = './src/viewsPackages/'
  await checkDire(path.join(process.cwd(), projectName), projectName); // 检测创建项目文件夹是否存在
  fs.readdir(pathName, function (err, files) {
    promptTypeList[1] = {
      "type": "list",
      "message": "请选择模版类型:",
      "name": "templateType",
      "choices": files
    }
    inquirer.prompt(promptTypeList).then(result => { //inquirer 交互问答
        const newPath = path.join("src/viewsPackages/", projectName+'/')
        const src = path.join("src/viewsPackages/", result.templateType+'/')
        let isExist = false
        //判断本地是否已经存在  包
        files.forEach(element => {
          if(element === projectName){
            isExist = true
          }
        });
        if(isExist){
          console.log(chalk.red(`包已经存在,项目模板创建失败`));
          return;
        }
        copyfile(src,newPath,projectName).then(()=>{
          writeBuild(path.join("src/viewsPackages/", projectName+'/build.json'),projectName)
          Promise.all([generateEnv(projectName,result),generateBuildCmd(projectName),upDateConfig(projectName)]).then(()=>{
            console.log(chalk.green(`🏇 The ${projectName} project template successfully create(项目模版创建成功)`));
          }).catch(e => ()=>{
            console.log(chalk.red(` The ${projectName} project template unsuccessfully create(项目模版创建失败)`));
          })
        }).catch(err=>{
          console.log(err)
        })
    });

  })


}

 
//写入build.json文件
const writeBuild = (path,projectName)=>{
  const dataJson = { }
  dataJson[projectName] = {}
  fs.writeFile(path, JSON.stringify(dataJson, "", "\t"), "utf-8", function (err) {
    if (err) {
      throw new Error("build.json写入失败");
    } else {
      console.log("build.json写入成功");
    }
  });
}

// 判断文件夹是否存在, 不存在创建一个
const isExist = (path) => { 
  if (!fs.existsSync(path)) {
    fs.mkdirSync(path)
  }
}

//fs 生成环境变量配置文件
const generateEnv = (projectName, result) => {
  return new Promise((resolve, reject) => {
    try {
      var writeStream = fs.createWriteStream(".env." + projectName);
      writeStream.write("# NODE 环境 \n");
      writeStream.write("NODE_ENV = " + result.env + " \n\n");
      writeStream.write("# 项目名称 \n");
      writeStream.write("VUE_APP_TITLE = " + projectName + "-Me \n\n");
      writeStream.write("VUE_APP_CLIENT_VERION = " + result.version + " \n\n");
      writeStream.write("VUE_APP_BASE_URL = '" + result.baseUrl + "' \n\n");
      writeStream.write("VUE_APP_QUICK_URL = '" + result.quickUrl + "' \n\n");
      writeStream.end();
      return resolve()
    } catch (error) {
      reject(error)
    }
  })
  
}

//生成打包，服务启动的命令行  package.json
const generateBuildCmd = (projectName) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./package.json', "utf8", function (err, data) {
      if (err) {
        reject(new Error("读取文件失败"))
        // throw new Error("读取文件失败");
      }
      const dataJson = JSON.parse(data)
      const {
        scripts
      } = dataJson
      const serKey = "serve-" + projectName
      const serveCmd = "vue-cli-service serve --dir " + projectName + " --build " + projectName
      const buildTestKey = "build-" + projectName + ":test"
      const buildTestCmd = "vue-cli-service build --dir " + projectName + " --mode commontest"
      const buildKey = "build-" + projectName
      const buildCmd = "vue-cli-service build --dir " + projectName + " --mode " + projectName
      scripts[serKey] = serveCmd
      scripts[buildTestKey] = buildTestCmd
      scripts[buildKey] = buildCmd
      fs.writeFile('./package.json', JSON.stringify(dataJson, "", "\t"), "utf-8", function (err) {
        if (err) {
          reject(new Error("package.json生成打包指令失败"))
          // throw new Error("package.json生成打包指令失败");
        } else {
          return resolve('package.json生成打包指令成功')
          // console.log("package.json生成打包指令成功");
        }
      });
    });
  })
 
}
//写入当前一些配置文件指令   本地文件config.js
const upDateConfig = (projectName) => {
  //写入当前一些配置文件指令
  
  // config.js
  return new Promise((resolve, reject) => {
    fs.readFile(__dirname + '/../packageName.json', "utf8", function (err, data) {
      if (err) {
        reject(new Error("读取文件失败"))
        // throw new Error("读取文件失败");
      }
      const dataJson = JSON.parse(data)
      dataJson.push(projectName)
      fs.writeFile(__dirname + '/../packageName.json', JSON.stringify(dataJson, "", "\t"), 'utf-8', (err) => {
        if (err){
          // console.log(err)
          reject(err)
        } 
        console.log(chalk.green('New template added!\n'))
        console.log(chalk.grey('The last template list is: \n'))
        console.log(config.buildCheckbox[0].choices)
        console.log('\n')
        return resolve('成功')
        // process.exit()
      })
    });
    
  })
  
}